package com.cloudpivot.receivales.meta.controller;

import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cloudpivot.receivales.meta.domain.FileResultRes;
import com.cloudpivot.receivales.meta.domain.OAWFFile;
import com.cloudpivot.receivales.meta.service.FileHandleService;
import com.cloudpivot.receivales.meta.service.PvDocumentService;
import com.cloudpivot.receivales.meta.service.QCFileService;
import com.cloudpivot.receivales.meta.view.ResponseMetaEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.util.*;

/**
 * 文档签名
 */

@Controller
@Slf4j
@RequestMapping("/signFile")
public class SignFileController {

    @Autowired
    private PvDocumentService pvDocumentService;

    @Autowired
    private FileHandleService fileHandleService;

    @Autowired
    private QCFileService qcFileService;

    @Value("${oadocurl.sourcedocpath}")
    private Integer SOURCEPATH;

    @Value("${oadocurl.pdfpath}")
    private Integer PDFPATH;

    @Value("${fontinfo.tmppath}")
    private String FILEPATH;


    /**
     * 从oa 流程 获取文件 不用
     */
    @ResponseBody
    @PostMapping("/oawffile")
    public String signFileFromOAWF(@Validated @RequestBody List<OAWFFile> list) {
//        log.info("获取到的对象----{}", JSONObject.toJSONString(list));
        List<FileResultRes> resList = new ArrayList<>();
        if (ObjectUtil.isNull(list)) {
            log.info("对象空,无法转换");
            return "对象空,无法转换";
        }

        try {
            for (OAWFFile entity : list) {
                //必须为带x的文档
//                if (!entity.getFileType().equals("docx") && !entity.getFileType().equals("xlsx")) {
//                    log.info("文档不符合转换要求");
//                    return ;
//                }
                //转pdf
                String sourceBase64 = entity.getFileBase64();
                File inFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp");
                BufferedOutputStream bos = null;
                FileOutputStream fos = null;
                byte[] bytes = Base64.getMimeDecoder().decode(sourceBase64);
                fos = new FileOutputStream(inFile);
                bos = new BufferedOutputStream(fos);
                bos.write(bytes);
                byte[] isCovPdfd = fileHandleService.fileToPdf(inFile,"docx");

                //增加签名
                File outFile = pvDocumentService.insertToSignToPdf(entity, isCovPdfd);
                FileReader fileReader = new FileReader(outFile);

                Base64.Encoder encoder = Base64.getEncoder();
                String pdfBase64 = encoder.encodeToString(fileReader.readBytes());
//                log.info("修改完的文件为:" + pdfBase64);
                //开始上传到oa知识库中
                //原件上传
                Integer retFileId = qcFileService.qcFileUpload(sourceBase64, pdfBase64, entity.getFileType(), entity.getFileName(), entity.getTitleName(), entity.getFilePath());
                FileResultRes res = new FileResultRes();
                res.setDocName(entity.getFileName());
                res.setDocId(retFileId);
                resList.add(res);
            }
            return JSONObject.toJSONString(resList);
        } catch (IOException e) {

            e.printStackTrace();
            return "系统异常";
        }

    }


    /**
     * 从oa 流程 获取文件 在用 (配合oa表单建模)
     */
    @ResponseBody
    @PostMapping("/oawfMdFile")
    public String signFileFromOAWFNew(@Validated @RequestBody List<OAWFFile> list) {
        log.info("获取到对象<---");
        List<FileResultRes> resList = new ArrayList<>();
        if (ObjectUtil.isNull(list)) {
            log.info("对象空,无法转换");
            return "对象空,无法转换";
        }
        try {
            for (OAWFFile entity : list) {
                //原件 base64
                String sourceBase64 = entity.getFileBase64();
//                File inFile = File.createTempFile(FILEPATH+UUID.randomUUID().toString(), ".tmp");
//                BufferedOutputStream bos = null;
//                FileOutputStream fos = null;
//                byte[] bytes = Base64.getMimeDecoder().decode(sourceBase64);
//                fos = new FileOutputStream(inFile);
//                bos = new BufferedOutputStream(fos);
//                bos.write(bytes);

                File inFile = new File(FILEPATH + UUID.randomUUID().toString() + ".docx");
                BufferedOutputStream bos = null;
                FileOutputStream fos = null;
                byte[] bytes = Base64.getMimeDecoder().decode(sourceBase64);
                fos = new FileOutputStream(inFile);
                bos = new BufferedOutputStream(fos);
                bos.write(bytes);
                byte[] isCovPdfd = fileHandleService.fileToPdf(inFile,"docx");
                log.info("开始做签名");
                if (Objects.isNull(isCovPdfd)) {
                    return "转换PDF时异常";
                }

                //增加签名
                File outFile = pvDocumentService.insertToSignToPdf(entity, isCovPdfd);
                FileReader fileReader = new FileReader(outFile);
                Base64.Encoder encoder = Base64.getEncoder();
                //pdf件 base64
                String pdfBase64 = encoder.encodeToString(fileReader.readBytes());
                //开始上传到oa知识库中
                //pdf上传
                log.info("开始pdf上传");
                Integer pdfFileId = qcFileService.qcFileUploadSigle(pdfBase64, entity.getFileType(), (entity.getFileName() + ".pdf"), entity.getTitleName(), Integer.valueOf(SOURCEPATH));

                FileResultRes res = new FileResultRes();
                res.setDocName(entity.getFileName());
                res.setDocId(pdfFileId);
                resList.add(res);
            }
            log.info("文档处理完成");
            return JSONObject.toJSONString(resList);
        } catch (IOException e) {
            e.printStackTrace();
            return "转换文档异常";
        }

    }

    /**
     * 从BPM 流程 获取文件
     * 返回 BPM 转义的 base64
     */
    @ResponseBody
    @PostMapping("/bpmWfMdFile")
    public JSONObject signFileFromBPMWFNew(@Validated @RequestBody List<OAWFFile> list) {
        log.info("获取到对象<---");
        List<FileResultRes> resList = new ArrayList<>();
        if (ObjectUtil.isNull(list)) {
            log.info("对象空,无法转换");
            return resultJson(-1, null);
        }else if(list.get(0).getFileType().contains("pdf")){
            JSONArray array = new JSONArray();
            JSONObject resJson = new JSONObject();
            byte[] bytes = Base64.getMimeDecoder().decode(list.get(0).getFileBase64());
            //增加签名
            File outFile = pvDocumentService.insertToSignToPdf(list.get(0), bytes);
            FileReader fileReader = new FileReader(outFile);
            Base64.Encoder encoder = Base64.getEncoder();
            //pdf件 base64
            String pdfBase64 = encoder.encodeToString(fileReader.readBytes());
            resJson.put("fileNewName", list.get(0).getFileName() + ".pdf");
            resJson.put("fileBase64", pdfBase64);
            array.add(resJson);
            return resultJson(0, array);
        }
        try {
            JSONArray array = new JSONArray();
            for (OAWFFile entity : list) {
                //原件 base64
                String sourceBase64 = entity.getFileBase64();

                File inFile = new File(FILEPATH + UUID.randomUUID().toString() + "." + entity.getFileType());
                BufferedOutputStream bos = null;
                FileOutputStream fos = null;
                byte[] bytes = Base64.getMimeDecoder().decode(sourceBase64);
                fos = new FileOutputStream(inFile);
                bos = new BufferedOutputStream(fos);
                bos.write(bytes);
                byte[] isCovPdfd = fileHandleService.fileToPdf(inFile, entity.getFileType());
                log.info("开始做签名");
                if (Objects.isNull(isCovPdfd)) {
                    return resultJson(-1, null);

                }

                //增加签名
                File outFile = pvDocumentService.insertToSignToPdf(entity, isCovPdfd);
                FileReader fileReader = new FileReader(outFile);
                Base64.Encoder encoder = Base64.getEncoder();
                //pdf件 base64
                String pdfBase64 = encoder.encodeToString(fileReader.readBytes());
                JSONObject resJson = new JSONObject();
                resJson.put("fileNewName", entity.getFileName() + ".pdf");
                resJson.put("fileBase64", pdfBase64);
                //直接返回BPM流程 base64字符串
                array.add(resJson);
            }

            log.info("文档处理完成");
            return resultJson(0, array);
        } catch (IOException e) {
            e.printStackTrace();
            return resultJson(-3, null);

        }

    }

    /**
     * bpm 用的 文件转换功能
     *
     * @param e
     * @return
     */

    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public String exceptionHandler(MethodArgumentNotValidException e) {
        return e.getBindingResult().getFieldError().getDefaultMessage();
    }

    private JSONObject resultJson(Integer code, JSONArray array) {

        JSONObject resJson = new JSONObject();
        resJson.put("code", code);
        resJson.put("msg", ResponseMetaEnum.getValue(code));
        resJson.put("result", array);
        return resJson;

    }
}
